const WXAPI = require('apifm-wxapi')

async function checkSession(){
  return new Promise((resolve, reject) => {
    wx.checkSession({
      success() {
        return resolve(true)
      },
      fail() {
        return resolve(false)
      }
    })
  })
}

// 检测登录状态，返回 true / false
async function checkHasLogined() {
  console.log("检查是否登陆")
  const token = wx.getStorageSync('token')
  if (!token) {
    console.log("token为空")
    return false
  }
  
  const checkTokenRes = await WXAPI.checkToken(token)
  if (checkTokenRes.code != 20000) {
    console.log("后端校验token失败")
    wx.removeStorageSync('token')
    return false
  }
  return true
}

// 用户登陆，如果没有注册则自动注册
async function login(page,data){
  console.log("用户登陆"+JSON.stringify(data))
  const _this = this 
  WXAPI.login_wx(data).then(function (res) {        
    
    if (res.code != 20000) {
      // 登录错误
      wx.showModal({
        title: '登陆失败',
        content: res.msg,
        showCancel: false
      })
      return;
    }
    console.log("login result : "+JSON.stringify(res))
    wx.setStorageSync('token', res.data.token)
    wx.setStorageSync('uid', res.data.uid)
    if ( page ) {
      page.onShow()
    }
  })
}


async function register(page) {
  console.log("用户信息注册:"+JSON.stringify(page))
  let _this = this;
  wx.login({
    success: function (res) {
      let code = res.code; // 微信登录接口返回的 code 参数，下面注册接口需要用到
      wx.getUserInfo({
        success: function (res) {
          let iv = res.iv;
          let encryptedData = res.encryptedData;
          let referrer = '' // 推荐人
          let referrer_storge = wx.getStorageSync('referrer');
          if (referrer_storge) {
            referrer = referrer_storge;
          }
          // 下面开始调用注册接口
          WXAPI.register_complex({
            code: code,
            encryptedData: encryptedData,
            iv: iv,
            referrer: referrer
          }).then(function (res) {
            _this.login(page);
          })
        }
      })
    }
  })
}

function loginOut(){
  wx.removeStorageSync('token')
  wx.removeStorageSync('uid')
}

async function checkAndAuthorize (scope) {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success(res) {
        if (!res.authSetting[scope]) {
          wx.authorize({
            scope: scope,
            success() {
              resolve() // 无返回参数
            },
            fail(e){
              console.error(e)
              // if (e.errMsg.indexof('auth deny') != -1) {
              //   wx.showToast({
              //     title: e.errMsg,
              //     icon: 'none'
              //   })
              // }
              wx.showModal({
                title: '无权操作',
                content: '需要获得您的授权',
                showCancel: false,
                confirmText: '立即授权',
                confirmColor: '#e64340',
                success(res) {
                  wx.openSetting();
                },
                fail(e){
                  console.error(e)
                  reject(e)
                },
              })
            }
          })
        } else {
          resolve() // 无返回参数
        }
      },
      fail(e){
        console.error(e)
        reject(e)
      }
    })
  })  
}


module.exports = {
  checkHasLogined: checkHasLogined,
  login: login,
  register: register,
  loginOut: loginOut,
  checkAndAuthorize: checkAndAuthorize
}